import { defineSource } from '../source';
import { ProcessedItem } from '../types'
import { myFetch } from "../utils/fetch"
import * as cheerio from "cheerio"
import iconv from "iconv-lite"
import logger from '../../framework/config/logger';

/**
 * 早晨报 排行榜 
 */
// export default defineSource({
//     zaobao: async (): Promise<ProcessedItem[]> => {
//         const response: ArrayBuffer = await myFetch("https://www.zaochenbao.com/realtime/", {
//           responseType: "arrayBuffer",
//         })
//         const base = "https://www.zaochenbao.com"
//         const utf8String = iconv.decode(Buffer.from(response), "gb2312")
//         const $ = cheerio.load(utf8String)
//         const $main = $("div.list-block>a.item")
//         const news: ProcessedItem[] = []
//         $main.each((_, el) => {
//           const a = $(el)
//           const url = a.attr("href")
//           const title = a.find(".eps")?.text()
//           const date = a.find(".pdt10")?.text().replace(/-\s/g, " ")
//           if (url && title && date) {
//             news.push({
//               url: base + url,
//               title,
//               id: url,
//               date,
//             })
//           }
//         })
//         return news.sort((m, n) => n.date! > m.date! ? 1 : -1)
//       }
// });

/**
 * 联合早报 https://www.zaobao.com/portalApi/realtime/reflash?pageSize=15
 */
interface Res {
    result: {
        [key: string]: International; // 使用索引签名代替硬编码的"2"、"3"等
    }
}

interface International {
    id: string; 
    title: string;    
    url: string;   
    mainSitemapName: string;
    contentPreview?: string;    
    publicationDate?: string;   
}

export default defineSource({
    zaobao: async (): Promise<ProcessedItem[]> => {
        const res: Res = await myFetch("https://www.zaobao.com/portalApi/realtime/reflash?pageSize=15")
        const internationalItems = Object.values(res?.result);
        return internationalItems.flat()
        .filter(s=>s.mainSitemapName === '国际')
        .map((k) => ({
            id: k.id,
            title: k.title,
            url: `https://www.zaobao.com/${k.url}/`,
            date: k.publicationDate,
            extra: {
                content: k.contentPreview, // HotValue是可选的，所以可能为undefined
                type: k.mainSitemapName
            },
        }));
    }
});